﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Devart.Data.Linq;
using System.Data.Linq.Mapping;

namespace KamLib
{
    public interface IEntitiesContainer
    {
        DataContext Entities { get; set; }
    }

    /// <summary>
    /// игнорировать [свойства] при копировании данных в Entity
    /// </summary>
    public class ReadOnlyAttribute : Attribute { }

    public static class EntityHelper
    {
        public static void CopyFrom<TSource, TEntity>(this TEntity entity, TSource src)
            where TEntity : class
        {
            ConvertAttribute.Copy(src, entity, (msrc, mdest) =>
            {
                var attr = (ColumnAttribute)Attribute.GetCustomAttribute(mdest, typeof(ColumnAttribute));
                if (attr != null && attr.IsPrimaryKey) return false;
                return Attribute.GetCustomAttribute(msrc, typeof(ReadOnlyAttribute)) == null;
            });
        }

        public static void CopyFrom<TEntity>(this TEntity entity, Dictionary<string, object> src)
            where TEntity : class
        {
            ConvertAttribute.CopyFrom(src, entity, (msrc, mdest) =>
            {
                var attr = (ColumnAttribute)Attribute.GetCustomAttribute(mdest, typeof(ColumnAttribute));
                return (attr == null || !attr.IsPrimaryKey);
            });
        }


        //public static PropertyInfo TableProp<TEntity>(this DataContext db)
        //    where TEntity : class
        //{
        //    var t = typeof(Table<TEntity>);
        //    return db.GetType().GetProperties().First(p => p.PropertyType == t);
        //}

        public static MemberInfo[] GetKeyFields<TEntity>()
            where TEntity : class
        {
            return typeof(TEntity).GetProperties().Where(a =>
            {
                var attr = (ColumnAttribute)Attribute.GetCustomAttribute(a, typeof(ColumnAttribute));
                return (attr != null && attr.IsPrimaryKey);
            }).ToArray();
        }
    }
}